<!-- 搜索 -->
<template>
  <view class="padding-sm">
    <!-- 搜索内容区 -->
    <view class="search-area pos-r w-full dflex-b">
      <view class="back" @click="toback()">
        <text class="iconfont icon-xiangzuo1" style="font-size: 40rpx" />
      </view>
      <view class="dflex-c flex1">
        <view class="iconfont icon-search pos-a" />
        <input
          class="uni-input"
          confirm-type="search"
          style="width: 100%; border-top-left-radius: 10px; border-bottom-left-radius: 10px"
          maxlength="20"
          placeholder="请输入关键字"
          @confirm="search()"
          v-model="keywords"
        />
      </view>

      <view class="search-text padding-tb-16 padding-lr-lg" @click="search()">搜索</view>
    </view>

    <!-- 搜索历史区 -->
    <view
      class="search-his padding bg-main w-full padding-bottom-xs border-radius"
      v-if="historyDatas && historyDatas.length > 0"
    >
      <view class="padding-bottom-sm dflex-b">
        <text class="fwb ft-dark">搜索历史</text>
        <view class="iconfont icon-huishouzhan dflex-c ft-dark" @click="clearHistory" />
      </view>
      <view class="dflex dflex-wrap-w fs-xs">
        <view
          class="item margin-right-sm margin-bottom-sm dflex bg-drak border-radius-lg padding-tb-xs padding-lr"
          v-for="(item, index) in historyDatas"
          :key="index"
          @click="search('history', item)"
        >
          <text>{{ item }}</text>
        </view>
      </view>
    </view>

    <view v-if="historyDatas && historyDatas.length > 0" class="gap" />

    <!-- 热门搜索区 -->
    <view
      class="search-hot padding bg-main w-full padding-bottom-xs border-radius"
      v-if="hotWords && hotWords.length > 0"
    >
      <view class="padding-bottom-sm dflex-b">
        <text class="fwb ft-dark"> 热门搜索 </text>
        <view class="iconfont icon-update dflex-c ft-dark" @click="refreshHot">换一批</view>
      </view>
      <view class="dflex dflex-wrap-w fs-xs">
        <view
          class="item margin-right-sm margin-bottom-sm dflex bg-drak border-radius-lg padding-tb-xs padding-lr"
          v-for="(item, index) in hotWords"
          :key="index"
          @click="search('hot', item)"
        >
          <text>{{ item }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { onLoad, onShow } from '@dcloudio/uni-app';
  import { hotWordsData } from '@/services/api/search/search';
  import config from '@/utils/config';
  import { url_params } from '@/utils';
  import { getCache, removeCache, setCache } from '@/utils/cache';
  import { HISTORY_WORD_KEY } from '@/enums/cacheEnum';
  import { isEmpty, isNullOrUnDef } from '@/utils/is';
  import { router } from '@/utils/router';

  /** 搜索关键字 */
  const keywords = ref('');
  /** 历史搜索 */
  const historyDatas: any = ref<string[]>([]);
  /** 热门搜索 */
  const hotWords = ref<string[]>([]);

  // 监听页面加载，其参数为上个页面传递的数据，参数类型为Object（用于页面传参）
  onLoad((options) => {
    if (options?.keywords) {
      keywords.value = options?.keywords;
    }
  });

  // 当 uni-app 启动，或从后台进入前台显示
  onShow(() => {
    // 加载数据
    loadData();
  });

  /**
   * 加载数据
   */
  const loadData = async () => {
    // 历史数据,从本地缓存中加载
    historyDatas.value = getCache<Array<string>>(HISTORY_WORD_KEY);
    // 热搜数据
    hotWordsData().then(({ data }) => {
      hotWords.value = data.data.hotWords;
    });
  };

  /**
   * 清空历史搜索
   */
  const clearHistory = () => {
    // 从本地缓存中删除历史数据
    removeCache(HISTORY_WORD_KEY);
    historyDatas.value = [];
  };

  /**
   * 换一批
   */
  const refreshHot = () => {
    hotWordsData().then(({ data }) => {
      hotWords.value = data.data?.hotWords;
    });
  };

  /**
   * 跳转搜索列表
   * @param type 搜索类别
   * @param value 值
   */
  const search = (type?: string, value?: string) => {
    console.log('进入search');
    // 若搜索词为空,则默认为热搜的第一个词
    // type为空是指手动输入搜索词
    if (isNullOrUnDef(type)) {
      keywords.value = isEmpty(keywords.value)
        ? (hotWords.value.length && hotWords.value[0]) || ''
        : keywords.value;
    } else {
      keywords.value = isEmpty(value) ? (hotWords.value.length && hotWords.value[0]) || '' : value;
    }
    // 历史数据
    let histories: any = getCache<Array<string>>(HISTORY_WORD_KEY);
    histories = isNullOrUnDef(histories) ? [] : histories;
    // 将搜索词放数组首位,若搜索词已存在缓存中则先删除再放首位
    let findIndex = histories ? histories.indexOf(keywords.value) : -1;
    if (findIndex == -1) {
      histories.unshift(keywords.value);
    } else {
      histories.splice(findIndex, 1);
      histories.unshift(keywords.value);
    }
    // 最多8个纪录
    histories.length > 8 && histories.pop();
    // 更新搜索历史
    historyDatas.value = histories;
    setCache(HISTORY_WORD_KEY, histories);

    // // 跳转搜索页
    // router.push(
    //   config.route.goodslist +
    //     url_params({
    //       keywords: keywords.value,
    //     }),
    // );
  };

  const toback = () => {
    router.back();
  };
</script>

<style lang="scss" scoped>
  .search-area {
    height: 120rpx;

    input {
      width: 560rpx;
      padding-left: 80rpx;
      height: 80rpx;
      line-height: 64rpx;
      background-color: #ffffff;
    }

    .back {
      padding: 0 10rpx;
    }

    .search-text {
      height: 80rpx;
      background: #ff6a6c;
      color: #fff;
      border-bottom-right-radius: 20rpx;
      border-top-right-radius: 20rpx;
    }

    .icon-search {
      top: 50%;
      left: 80rpx;
      transform: translate(0, -50%);
      z-index: 1;

      text {
        color: #c0c0c0;
      }
    }
  }

  .search-his {
    .iconfont {
      height: 14rpx;
      font-size: 20rpx;
      line-height: 1;
      margin-left: 4rpx;
    }
  }

  .search-hot {
    .iconfont {
      height: 14rpx;
      font-size: 20rpx;
      line-height: 1;
      margin-left: 4rpx;
    }
  }
</style>
